package com.siwei.infoextract.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.siwei.infoextract.SystemConfig;
import com.siwei.infoextract.util.Utility;
import com.siwei.infoextract.wrapper.featureextract.AnnotationOutputter;
import com.siwei.infoextract.wrapper.parser.DomNode;
import com.siwei.infoextract.wrapper.trainer.CNTrainer;

public class TrainServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		service(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		service(request, response);
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Set factory constraints
		//factory.setSizeThreshold(yourMaxMemorySize);
		//factory.setRepository(yourTempDirectory);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Set overall request size constraint
		// upload.setSizeMax(yourMaxRequestSize);

		// Parse the request
		try {
			List /* FileItem */ items = upload.parseRequest(request);
			
			// Process the uploaded items
			String uploadDir = SystemConfig.getValue("file.upload.dir");
			File uploadFile = null;
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (!item.isFormField()) {
			    	
			    	if (item.getName() != null && !item.getName().trim().equals("")) {
			    		uploadFile = new File(uploadDir + File.separator + item.getName());
				        item.write(uploadFile);
			    	}
			        break;
			    } else {
			        // skip form field in this servlet
			    }
			}

			if (uploadFile != null) {
				DomNode root = Utility.parseDomNodeFromFile(uploadFile.getAbsolutePath());
				String annotationOutputDir = SystemConfig.getValue("file.trained.output");
				AnnotationOutputter annotationOutputter = new AnnotationOutputter(annotationOutputDir);
				annotationOutputter.output(root);
				
				CNTrainer trainer = new CNTrainer(
						SystemConfig.getValue("train.executable"),
						SystemConfig.getValue("train.attribute.PHONE"),
						SystemConfig.getValue("train.examples.PHONE"),
						SystemConfig.getValue("ruleengine.rulefile.PHONE"));
				trainer.train();

				trainer = new CNTrainer(
						SystemConfig.getValue("train.executable"),
						SystemConfig.getValue("train.attribute.ADDRESS"),
						SystemConfig.getValue("train.examples.ADDRESS"),
						SystemConfig.getValue("ruleengine.rulefile.ADDRESS"));
				trainer.train();
				
				trainer = new CNTrainer(
						SystemConfig.getValue("train.executable"),
						SystemConfig.getValue("train.attribute.TITLE"),
						SystemConfig.getValue("train.examples.TITLE"),
						SystemConfig.getValue("ruleengine.rulefile.TITLE"));
				trainer.train();
			}
		} catch (FileUploadException fue) {
			fue.printStackTrace();
			throw new IOException(fue.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			throw new IOException(e.getMessage());
		}

		response.sendRedirect(request.getContextPath() + "/index.jsp");
	}
}
